import TouchLayer from "@ke/touchlayer";
import React, { useState, useEffect, useCallback } from "react";
import "./Main.css";
import { Monitor } from "./Monitor";
import PageCover from "./Pages";

const pagesList = [
  import("./Pages/0"),
  import("./Pages/0a"),
  import("./Pages/0b"),
  import("./Pages/1"),
  import("./Pages/2"),
  import("./Pages/3"),
  import("./Pages/4"),
  import("./Pages/5"),
  import("./Pages/5a"),
  import("./Pages/5b"),
  import("./Pages/6"),
];
let dragDistance = 0;
export function Main() {
  const [currentPage, setCurrentPage] = useState(0);
  const setPage = useCallback((index) => {
    setCurrentPage(Math.max(0, Math.min(pagesList.length - 1, index)));
    dragDistance = index * window.innerHeight;
    document.getElementById(
      "cover"
    ).style.cssText = `transform:translateY(${-dragDistance}px);transition:transform 0.5s ease;`;
  }, []);
  const [pages, setPages] = useState([]);
  useEffect(() => {
    let pagesArray = [];
    Promise.all(
      pagesList.map((item, index) => {
        return item.then((res) => {
          pagesArray[index] = res.default;
        });
      })
    ).then(() => {
      setPages(pagesArray);
    });
  }, []);
  return (
    <div>
      <TouchLayer
        noInertance
        wheelY
        onDragY={(e) => {
          dragDistance = Math.max(
            0,
            Math.min(window.innerHeight * (pages.length - 1), dragDistance - e)
          );
          document.getElementById(
            "cover"
          ).style.cssText = `transform:translateY(${-dragDistance}px);`;
          let page = Math.max(
            0,
            Math.min(
              Math.round(dragDistance / window.innerHeight),
              pagesList.length - 1
            )
          );
          if (page !== currentPage) {
            setCurrentPage(page);
          }
        }}
        // onDragEnd={() => {
        //   setPage(currentPage);
        // }}
      >
        <div id="cover" style={{ height: pages.length * window.innerHeight }}>
          {pages.map((Page, index) => {
            return (
              <PageCover page={index} currentPage={currentPage} key={index}>
                <Page
                  page={index}
                  nextPage={() => setPage(index + 1)}
                  prevPage={() => setPage(index - 1)}
                  setCurrentPage={setPage}
                />
              </PageCover>
            );
          })}
        </div>
      </TouchLayer>
      <Monitor
        pages={pages}
        currentPage={currentPage}
        setCurrentPage={setPage}
      />
    </div>
  );
}
